import React from 'react';
import { Modal, Form, Button, Space, Input } from 'antd';
import { useEffect } from 'react';
import API from '@/api';
import { connect, useModel } from 'umi';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { checkPhone, checkLandPhone } from '@/utils/util';
const CreateModal = ({ visible, onCreate, onCancel, id, status }) => {
  const [form] = Form.useForm();
  const { initialState = {} } = useModel('@@initialState');
  const { orgName } = initialState.info;
  const initState = () => {
    if (id) {
      API.showEUP({ id }).then((res) => {
        if (res?.t) {
          const { emergencyPersonList } = res.t;
          form.setFieldsValue({ emergencyPersonList });
        }
      });
    } else {
      form.setFieldsValue({
        emergencyPersonList: [{}],
      });
    }
  };
  useEffect(() => {
    if (visible) {
      form.resetFields();
      initState();
    }
  }, [visible]);
  const titleMap = ['新增应急支撑人员', '应急支撑人员详情', '编辑应急支撑人员'];
  return (
    <Modal
      visible={visible}
      title={titleMap[status]}
      width={1200}
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      maskClosable={status === 1}
      destroyOnClose
      footer={status === 1 ? null : undefined}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            console.log(values);
            values.emergencyPersonList.forEach((element) => {
              if (element.tel == '') {
                element.tel = null;
              }
            });
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        name="form_in_modal"
        preserve={false}
        className="form-x"
      >
        <Form.List
          name="emergencyPersonList"
          rules={[
            {
              validator: async (_, names) => {
                if (!names || names.length < 1) {
                  return Promise.reject(new Error('至少有一名应急支撑人员'));
                }
              },
            },
          ]}
        >
          {(fields, { add, remove, errors }) => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Space
                  key={key}
                  size={20}
                  style={{ marginBottom: 8 }}
                  align="baseline"
                >
                  <Form.Item
                    {...restField}
                    name={[name, 'name']}
                    label="姓名"
                    rules={[{ required: true, message: '请输入姓名' }]}
                  >
                    <Input placeholder="请输入" readOnly={status === 1} />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    label="单位"
                    name={[name, 'orgName']}
                    initialValue={orgName}
                  >
                    <Input disabled />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    name={[name, 'tel']}
                    label="办公电话"
                    rules={[{ validator: checkLandPhone }]}
                  >
                    <Input placeholder="请输入" readOnly={status === 1} />
                  </Form.Item>
                  <Form.Item
                    {...restField}
                    label="移动电话"
                    name={[name, 'phone']}
                    rules={[{ required: true, validator: checkPhone }]}
                  >
                    <Input placeholder="请输入" readOnly={status === 1} />
                  </Form.Item>
                  {key > 0 && status !== 1 ? (
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  ) : (
                    <div style={{ width: 14 }}></div>
                  )}
                </Space>
              ))}
              <Form.Item>
                {status !== 1 ? (
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                  >
                    添加应急支撑人员
                  </Button>
                ) : (
                  ''
                )}
                <Form.ErrorList errors={errors} />
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
};

export default connect(({ dict }) => ({
  orgOptions: dict.orgOptions,
}))(CreateModal);
